import { ref } from 'vue'
import { cloneDeep } from 'lodash'
import { Tools } from '@/utils'
import { fetchMenuList } from '@/api'

const { listToTree } = Tools

const tableTree = ref([])
const menuTree = ref([])
const allCheckKeys = []

const getAllCheckKeys = list => {
  list.forEach(item => {
    if (item.children) {
      getAllCheckKeys(item.children)
    } else {
      allCheckKeys.push(item.menuId)
    }
  })
}

/**
 * 获取菜单列表
 */
const getMenuList = async (subjectId, checkKeys) => {
  const listRes = await fetchMenuList({ subjectId })
  if (!listRes.code) {
    listRes.sort((o1, o2) => {
      if (o1.parentId === o2.parentId) {
        return o1.orderNum - o2.orderNum
      } else {
        return o1.parentId - o2.parentId
      }
    })
    tableTree.value = listToTree(cloneDeep(listRes), { idName: 'menuId', pidName: 'parentId' })
    const subList = [{ menuId: '0', parentId: '-1', name: '根目录' }, ...listRes.filter(item => item.type < 2)]
    menuTree.value = listToTree(cloneDeep(subList), { idName: 'menuId', pidName: 'parentId' }, '-1')
    if (checkKeys && checkKeys.length) {
      const checkList = listRes.filter(item => checkKeys.includes(item.menuId))
      const checkTree = listToTree(cloneDeep(checkList), { idName: 'menuId', pidName: 'parentId' })
      getAllCheckKeys(checkTree)
    }
    return
  }
  console.log(listRes)
}

export default {
  tableTree,
  menuTree,
  allCheckKeys,
  getMenuList
}
